var http = require('http');

let db = [];

var server = http.createServer((req,res) => {

    res.setHeader('content-type', 'text/plain;charset=utf-8')

    const { path, params } = parseUrl(req);

    if(path === '/list') {
        res.end( JSON.stringify(db) );
        return;
    }

    if(path === '/add') {
        const newItem = params.content;

        if(!newItem) {
            res.end("添加失败, content 参数不能为空");
            return;
        }
        db.push(newItem);

        res.end( JSON.stringify({
            msg: '添加成功',
            length: db.length
        }) );
        return;
    }

    if(path === '/remove') {
        const index = params.index;

        if(isNaN(index)){
            res.end("删除失败, 没有 index 参数");
            return;
        }

        if(index < 0 || index >= db.length) {
            res.end("删除失败, 删除范围出错");
            return;
        }

        db = db.filter( (item, arrIndex) => {
            return arrIndex !== parseInt( index );
        });

        return res.end( JSON.stringify({
            msg: '删除成功',
            length: db.length
        }) );;
    }

    res.setHeader('content-type', 'text/html;charset=utf-8')

    res.end(`
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>todoList</title>
</head>
<body>
    <div>
        <h3>带办事项</h3>
        <ul>
        ${
            db.map(item=> `<li>${item}</li>`).join('\n')
        }
        </ul>

        <input />
    </div>
    
</body>
</html>
    `);

});

function parseUrl (req) {
    const url = req.url; // /add?a=3&b=4
    const [path = '', paramsStr = ''] = url.split('?'); 

    // paramsStr = a=3&b=4  ;

    const pairs = paramsStr.split('&');
    const params = {};

    pairs.forEach(pair => {
        const [key, value] = pair.split('=');
        params[key] = value;
    });


    return {
        path,
        params,
    };
}


server.listen(3000);